import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
  // 创建带有中间件功能的 supabase 客户端
  const res = NextResponse.next()
  const supabase = createMiddlewareClient({ req, res })

  // 检查会话
  const {
    data: { session },
  } = await supabase.auth.getSession()

  // 如果是 /products/ 下的子页面且用户未登录，重定向到登录页
  if (req.nextUrl.pathname.startsWith('/products/') && !session) {
    const redirectUrl = new URL('/login', req.url)
    // 添加原始URL作为重定向参数，这样登录后可以回到原来的页面
    redirectUrl.searchParams.set('redirectTo', req.nextUrl.pathname)
    return NextResponse.redirect(redirectUrl)
  }

  return res
}

// 配置匹配的路由
export const config = {
  matcher: '/products/:path*'
} 